<template>
  <div>
    <van-popup v-model="cityShow" round position="bottom" @close="cityClose">
      <van-cascader
        v-model="cityCode"
        title="请选择所在地区"
        :options="cityOptions"
        :field-names="cityFieldNames"
        @close="cityClose"
        @change="cityChange"/>
    </van-popup>
  </div>
</template>

<script>
import { getDoctorAa12List } from 'api/userInfo'

export default {
  name: 'CityPopup',
  props: {},
  data() {
    return {
      cityShow: true,
      cityCode: '',
      cityName: '',
      cityOptions: [],
      cityFieldNames: {
        text: 'AAB302',
        value: 'AAB301',
        children: 'children'
      }
    }
  }
  ,
  mounted() {
    this.loadRegionChild([], '000000000000', 'first')
  }
  ,
  methods: {
    findRegionOption(regionOptions, regionArr) {
      if (JSON.stringify(regionOptions) == '[]' || JSON.stringify(regionOptions) == '[]') {
        return null
      }
      // 取数组的第一项
      let getRegionArr = [...regionArr]
      let target = getRegionArr.shift()
      let regionId = target.AAB301
      let regionOption = regionOptions.filter(regionOption => regionOption.AAB301 === regionId)
      if (regionOption.length == 0) {
        return null
      }
      let tailRegionArr = regionOption[0]
      if (getRegionArr.length == 0) {
        return tailRegionArr
      }
      return this.findRegionOption(tailRegionArr.children, getRegionArr)
    }
    ,
    loadRegionChild(regionArr, regionKey, load) {
      let regionOptions = this.cityOptions
      let regionOptionInUI = this.findRegionOption(regionOptions, regionArr)
      getDoctorAa12List({ parentid: regionKey })
        .then(res => {
          if (res.data != '[]') {

            let regionHiera = JSON.parse(res.data)
            regionHiera = regionHiera.map(item => {
              return {
                'AAB301': item.AAB301,
                'AAB302': item.AAB302,
                'ISLEAF': item.ISLEAF,
                'PARENTID': item.PARENTID,
                'children': []
              }
            })
            if (load == 'first') {
              this.cityOptions = regionHiera
            } else {
              this.$set(regionOptionInUI, 'children', regionHiera)
              regionOptionInUI.children = regionHiera
            }
          } else {
            let regionName = regionArr[regionArr.length - 1].AAB302
            this.cityCode = ''
            this.cityShow = false
            this.$emit('cityChange', { regionKey, regionName })
          }
        })
    }
    ,
    cityChange({ value, selectedOptions }) {
      this.loadRegionChild(selectedOptions, value)
    },
    cityClose() {
      this.cityShow = false
      this.$emit('cityClose')
    }

  }
}
</script>

<style scoped>

</style>
